using System.Collections.Generic;
using System.IO;
using UnityEditor;
using UnityEditor.U2D;
using UnityEngine;
using UnityEngine.U2D;

namespace CGF
{
    [InitializeOnLoad]
    public class SpriteAtlasCreater
    {
        [MenuItem("Assets/创建 Sprite Atlas")]
        public static void CreateSpriteAtlas()
        {
            Object[] objs = Selection.GetFiltered(typeof(DefaultAsset), SelectionMode.Assets);
            if (objs.Length == 0)
            {
                EditorUtility.DisplayDialog("提示", "请选择一个目录", "确定");
                return;
            }
            for (int i = 0; i < objs.Length; i++)
            {
                CreateOneFolder(objs[i]);
            }
        }

        private static void CreateOneFolder(Object folder)
        {
            if (folder != null)
            {
                SpriteAtlas atlas = new SpriteAtlas();
                SpriteAtlasPackingSettings packSet = new SpriteAtlasPackingSettings()
                {
                    blockOffset = 1,
                    enableRotation = false,
                    enableTightPacking = false,
                    padding = 4,
                };
                atlas.SetPackingSettings(packSet);
                SpriteAtlasTextureSettings textureSet = new SpriteAtlasTextureSettings()
                {
                    readable = true,
                    generateMipMaps = false,
                    sRGB = true,
                    filterMode = FilterMode.Bilinear,
                };
                atlas.SetTextureSettings(textureSet);
                string folderPath = AssetDatabase.GetAssetPath(folder);
                string fileName = folderPath.Substring(folderPath.LastIndexOf("/") + 1);
                string savePath = $"{folderPath}/{fileName}.spriteatlas";
                AssetDatabase.CreateAsset(atlas, savePath);

                //设置图片最大尺寸
                var atlasSetting = atlas.GetPlatformSettings("DefaultTexturePlatform");
                atlasSetting.maxTextureSize = 4096;
                atlas.SetPlatformSettings(atlasSetting);

                SpriteAtlasExtensions.Add(atlas, new Object[] { folder });
                AssetDatabase.SaveAssets();
            }
        }

    }
}